package com.mhl.campuscabinet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;

import com.mhl.adapter.ProductAdapter;
import com.mhl.adapter.ProductImageAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Msg;
import com.mhl.adapter.MsgAdapter;
import com.mhl.entity.Product;
import com.mhl.entity.User;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ProductActivity extends AppCompatActivity implements View.OnClickListener {

    Boolean fllow,collect;
    Double price;
    int providerId;
    String username,date,info,productname;
    int itemId;
    int itemState;
    int itemStarNum;

    private List<Msg> msgList = new ArrayList<>();
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;
    private Socket socketSend;
    private String ip="192.168.31.115"; //修改
    private String port="6667";
    DataInputStream dis;
    DataOutputStream dos;
    boolean isRunning = false;
    private String recMsg;
    private boolean isSend=false;
    private int userId;
    ImageView provider_profile;


    TextView tusername,tdate,tinfo,tprice,tproductname;
    ImageButton bcomment;
    ArrayList<String> urls = new ArrayList<>();
    ArrayList<Integer> tags = new ArrayList<>();
    ArrayList<Integer> star_list = new ArrayList<>();

    private RecyclerView imageRecyclerView;
    private List<String> pilist;
    private ProductImageAdapter productImageAdapter;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:{
                    productAdapter.notifyDataSetChanged();
                }
                break;
                case 2:{

                }
                break;
                default:
                break;
            }

        }
    };

    // 商品详情页内推荐
    //ArrayList<String> tag; // 同类标签名，麻烦也通过Intent传过来
    private RecyclerView likeRecyclerView;
    private ArrayList<Product> productList = new ArrayList<>();
    private ProductAdapter productAdapter;

    // 底部栏组件
    private TextView iWant;
    private ImageButton offerPrice;
    private TextView sellsame;
    //private RadioButton collectBtn;
    private CheckBox collect_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product);


        initData();
        initView();
        initLike();
    }

    @SuppressLint({"SetTextI18n", "WrongViewCast"})
    public void initView(){
        tusername = findViewById(R.id.username);
        tproductname = findViewById(R.id.productname);
        tdate = findViewById(R.id.releasetime);
        tinfo = findViewById(R.id.describe);
        tprice = findViewById(R.id.price);
        bcomment = findViewById(R.id.comment);
        collect_btn = findViewById(R.id.collect);
        provider_profile = findViewById(R.id.headportrait);
        Glide.with(this).load("https://img2.baidu.com/it/u=3329353302,71880253&fm=26&fmt=auto").into(provider_profile);
        System.out.println(star_list);
        for (int i = 0; i < star_list.size(); i++) {
            if(star_list.get(i).equals(User.getInstance().getUserId())){
                System.out.println("找到该用户");
                collect_btn.setChecked(true);
                break;
            }
        }

        collect_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    collectItem();
                    try {
                        Thread.sleep(500);
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                } else {
                    unCollectItem();
                    try {
                        Thread.sleep(500);
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });

        //设置值
        tusername.setText(username);
        tproductname.setText(productname);
        tdate.setText(date);
        tinfo.setText(info);

        System.out.println("price is :" + price+" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        tprice.setText(price.toString());
        pilist = new ArrayList<>();
        pilist.addAll(urls);
        imageRecyclerView = (RecyclerView)findViewById(R.id.list_productimage);
        LinearLayoutManager imageLayoutManager = new LinearLayoutManager(this );
        //设置布局管理器
        imageRecyclerView.setLayoutManager(imageLayoutManager);
        //设置图片Adapter
        productImageAdapter = new ProductImageAdapter(pilist, this);
        imageRecyclerView.setAdapter(productImageAdapter);

//        collectBtn.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//             @Override
//            public void onCheckedChanged(RadioGroup radioGroup, int checkdId) {
//                                 RadioButton rb = findViewById(checkdId);
//                                 String s = rb.getText().toString();
//                                t.setText("单击了" +s);
//                            }
//         });

        bcomment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ProductActivity.this,CommentAcyivity.class);
                //此处进行获取评论列表操作,可将信息存到intent中，再在CommentActivity中调用
                intent.putExtra("item_id",itemId);
                startActivity(intent);
            }
        });
        iWant = (TextView)findViewById(R.id.iwant);
        offerPrice = (ImageButton)findViewById(R.id.offerprice);
        sellsame = findViewById(R.id.sellsame);

        iWant.setOnClickListener(this);

        if(providerId == User.getInstance().getUserId()){
            iWant.setClickable(false);
            iWant.setBackgroundResource(R.drawable.ic_sellsame);
        }

        offerPrice.setOnClickListener(this);
        sellsame.setOnClickListener(this);
    }


    public void initData(){
        //获取意图对象
        Intent intent = getIntent();
        //获取传递的值
        itemId = intent.getIntExtra("item_id",0);
        providerId = intent.getIntExtra("provider_id", 0);
        price = intent.getDoubleExtra("price",0);
        date = intent.getStringExtra("date");
        info = intent.getStringExtra("description");
        urls = intent.getStringArrayListExtra("url");
        tags = intent.getIntegerArrayListExtra("tag");
        username = intent.getStringExtra("provider_name");
        star_list = intent.getIntegerArrayListExtra("star_list");
        productname = intent.getStringExtra("name");
        System.out.println(urls);

    }

    // 加载猜你喜欢
    public void initLike() {
        // 获取意图对象
        Intent intent = getIntent();
        // 获取传递的值
        tags = intent.getIntegerArrayListExtra("tag");
        System.out.println("该商品详情页应该推荐的tag是：" + tags.get(0));
        likeRecyclerView = (RecyclerView)findViewById(R.id.like_recycler_view);
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        likeRecyclerView.setLayoutManager(layoutManager);
        productAdapter = new ProductAdapter(productList, this);
        likeRecyclerView.setAdapter(productAdapter);


        /**
         * 请客户端发出请求将同tag商品放到productList
         * 请求：tag
         * 响应：product json array
         */


        //todo

        JSONObject userJson = new JSONObject();
        System.out.println("进入猜你喜欢");
        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            userJson.put("tag", tags.get(0));
            String json = userJson.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

            OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "tag/get/merchandise", requestBody, new Callback() {
                Handler h = handler;

                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    System.out.println("接收到服务器响应");
                    final String ItemsString = response.body().string();
                    try {
                        int state = 1;
                        try {
                            JSONObject errcodeJson = new JSONObject(ItemsString);
                            state = errcodeJson.getInt("errcode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Looper.prepare();
                        if (state == 1) {
                            Toast.makeText(ProductActivity.this, "Can't find this tag", Toast.LENGTH_SHORT).show();
                        } else if (state == 2) {
                            Toast.makeText(ProductActivity.this, "key error", Toast.LENGTH_SHORT).show();
                        } else {
                            JSONObject itemsJson = new JSONObject(ItemsString);
                            JSONArray itemArray = itemsJson.getJSONArray("data");
                            for (int i = 0; i < itemArray.length(); i++) {
                                JSONObject item = itemArray.getJSONObject(i);
                                Product product = new Product();
                                product.setPrice(item.getDouble("pre_price"));
                                product.setName(item.getString("name"));
                                JSONArray urls = item.getJSONArray("url_list");
                                product.setURL(urls.getString(0));

                                product.setId(item.getInt("id"));
                                productList.add(product);
                            }
                            h.sendEmptyMessage(1);
                        }
                        Looper.loop();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            });
        }catch (JSONException e){
            e.printStackTrace();
        }


    }

    private void ensureOrder(){

        JSONObject ensure = new JSONObject();
        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            ensure.put("buyer_id", User.getInstance().getUserId());
            ensure.put("merchandise_id",itemId);
            String json = ensure.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

            OkHttpUtils.sendOkHttpResponse("http://192.168.31.93:8000/api/merchandise/order", requestBody, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String resString = response.body().string();
                    int state = 1;
                    try {
                        JSONObject errcodeJson = new JSONObject(resString);
                        state = errcodeJson.getInt("errcode");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Looper.prepare();
                    if (state != 0) {
                        Toast.makeText(ProductActivity.this, "Can't ensure the order", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(ProductActivity.this, "Order succeeded", Toast.LENGTH_SHORT).show();
                    }
                    Looper.loop();

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iwant:{
                MaterialDialog dialog = new MaterialDialog.Builder(this)
                        .title("确认购买")
                        .content("建议先在出价和商家沟通好交付的地点和价格~或者点击确认系统会自动为卖家发送消息方便联系亲呢")
                        .positiveText("确认")
                        .negativeText("取消").build();

                dialog.getBuilder().onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    userId=User.getUserId();
                                    Socket socket = new Socket(ip, Integer.parseInt(port));
                                    String content = "您好我想要" + productname;
                                    StringBuilder sb = new StringBuilder();
                                    socketSend = new Socket(ip,Integer.parseInt(port));
                                    dos = new DataOutputStream(socketSend.getOutputStream());
                                    sb.append(content).append("\n").append(userId).append("\n"+providerId);
                                    content = sb.toString();
                                    //输出流
                                    dos.writeUTF(content);
                                    //关闭资源
                                    dos.close();
                                    ensureOrder();
                                } catch (UnknownHostException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                            }
                        }).start();

                    }

                });
                dialog.show();
            }
                break;
            case R.id.offerprice:{
                EditText price = new EditText(this);
                MaterialDialog dialog = new MaterialDialog.Builder(this)
                        .title("出价")
                        .content("出价消息会发给卖家方便和您联系呦~")
                        .positiveText("确认")
                        .negativeText("取消")
                        .inputType(InputType.TYPE_CLASS_NUMBER)
                        .input("输入出价", null, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull @NotNull MaterialDialog dialog, CharSequence input) {
                                //TODO
                                Toast.makeText(ProductActivity.this, "您已出价" + input + "元", Toast.LENGTH_SHORT).show();
                            }
                        })

                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                //TODO

                            }
                        })
                        .build();
                dialog.show();
            }
                break;
            case R.id.sellsame:{
                Intent intent = new Intent(ProductActivity.this,MainActivity.class);
                intent.putExtra("id",2);
                //put tag

                startActivity(intent);
            }
                break;
            default:
                break;
        }
    }

    public void collectItem(){
        JSONObject req = new JSONObject();

        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            req.put("user_id", User.getInstance().getUserId());
            req.put("merchandise_id",itemId);
            String json = req.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

            OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "star/create", requestBody, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String resString = response.body().string();
                    int state = 1;
                    try {
                        JSONObject errcodeJson = new JSONObject(resString);
                        state = errcodeJson.getInt("errcode");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Looper.prepare();
                    if (state != 0) {
                        Toast.makeText(ProductActivity.this, "Can't collect this product", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(ProductActivity.this, "Collect succeeded", Toast.LENGTH_SHORT).show();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                collect_btn.setChecked(true);
                            }
                        });
                    }
                    Looper.loop();

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void unCollectItem(){
        JSONObject req = new JSONObject();

        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            req.put("user_id", User.getInstance().getUserId());
            req.put("merchandise_id",itemId);
            String json = req.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

            OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "star/delete", requestBody, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String resString = response.body().string();
                    int state = 1;
                    try {
                        JSONObject errcodeJson = new JSONObject(resString);
                        state = errcodeJson.getInt("errcode");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Looper.prepare();
                    if (state != 0) {
                        Toast.makeText(ProductActivity.this, "Can't cancel collecting this product", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(ProductActivity.this, "Cancel collecting succeeded", Toast.LENGTH_SHORT).show();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                collect_btn.setChecked(false);
                            }
                        });
                    }
                    Looper.loop();

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}